import { useCallback, useEffect, useMemo, useState } from 'react'
import { View, Text, Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { sendLoginCode, loginWithCode } from '@/services/auth'

import './index.scss'

const PHONE_REGEX = /^1[3-9]\d{9}$/
const COUNTDOWN_SECONDS = 60

const LoginPage = () => {
  const [phone, setPhone] = useState('')
  const [code, setCode] = useState('')
  const [countdown, setCountdown] = useState(0)
  const [sendingCode, setSendingCode] = useState(false)
  const [loginLoading, setLoginLoading] = useState(false)

  useEffect(() => {
    if (countdown <= 0) return
    const timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(timer)
          return 0
        }
        return prev - 1
      })
    }, 1000)
    return () => clearInterval(timer)
  }, [countdown])

  const canSendCode = useMemo(() => {
    return PHONE_REGEX.test(phone) && countdown === 0 && !sendingCode
  }, [phone, countdown, sendingCode])

  const handleSendCode = useCallback(async () => {
    if (!PHONE_REGEX.test(phone)) {
      Taro.showToast({ title: '请输入正确手机号', icon: 'none' })
      return
    }
    if (!canSendCode) return
    setSendingCode(true)
    try {
      await sendLoginCode(phone.trim())
      Taro.showToast({ title: '验证码已发送', icon: 'none' })
      setCountdown(COUNTDOWN_SECONDS)
    } catch (error) {
      // 错误提示在 request 层处理
    } finally {
      setSendingCode(false)
    }
  }, [phone, canSendCode])

  const backToPrevious = useCallback(() => {
    Taro.navigateBack({
      fail: () => {
        Taro.switchTab({ url: '/pages/index/index' })
      }
    })
  }, [])

  const handleLogin = useCallback(async () => {
    const trimmedPhone = phone.trim()
    const trimmedCode = code.trim()
    if (!PHONE_REGEX.test(trimmedPhone)) {
      Taro.showToast({ title: '请输入正确手机号', icon: 'none' })
      return
    }
    if (!trimmedCode) {
      Taro.showToast({ title: '请输入验证码', icon: 'none' })
      return
    }
    if (loginLoading) return
    setLoginLoading(true)
    try {
      await loginWithCode({ phone: trimmedPhone, code: trimmedCode })
      Taro.showToast({ title: '登录成功', icon: 'success' })
      setTimeout(backToPrevious, 400)
    } catch (error) {
      // request 层已提示
    } finally {
      setLoginLoading(false)
    }
  }, [phone, code, loginLoading, backToPrevious])

  return (
    <View className='login-page'>
      <View className='login-page__card'>
        <Text className='login-page__title'>手机号登录</Text>
        <Text className='login-page__subtitle'>输入手机号并验证后即可访问所有功能</Text>

        <View className='login-page__field'>
          <Text className='login-page__label'>手机号</Text>
          <Input
            className='login-page__input'
            type='number'
            maxLength={11}
            placeholder='请输入11位手机号'
            value={phone}
            onInput={(event) => setPhone(event.detail.value.replace(/[^\d]/g, ''))}
          />
        </View>

        <View className='login-page__field'>
          <Text className='login-page__label'>验证码</Text>
          <View className='login-page__code-row'>
            <Input
              className='login-page__input'
              type='number'
              maxLength={6}
              placeholder='请输入验证码'
              value={code}
              onInput={(event) => setCode(event.detail.value.replace(/[^\d]/g, ''))}
            />
            <View
              className={`login-page__code-btn${
                canSendCode ? '' : ' is-disabled'
              }`}
              onClick={handleSendCode}
            >
              {countdown > 0 ? `${countdown}s后重发` : '获取验证码'}
            </View>
          </View>
        </View>

        <View
          className={`login-page__submit${
            loginLoading ? ' is-loading' : ''
          }`}
          onClick={handleLogin}
        >
          {loginLoading ? '登录中...' : '登录'}
        </View>
      </View>
    </View>
  )
}

export default LoginPage
